package cn.dev.mybatis.handler.parse;

import cn.dev.mybatis.bean.SqlObject;

import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TokenParser {

    private static final int INIT_LENGTH = 3;

    private static final String PARAM_REG = "#\\{\\w+\\}";

    public void parseSql(String sql, SqlObject sqlObject) {
        if (!sql.matches(".*" + PARAM_REG + ".*")) {
            sqlObject.setParamNames(null);
            sqlObject.setOriginSql(sql);
            return;
        }
        Pattern pattern = Pattern.compile(PARAM_REG);
        Matcher matcher = pattern.matcher(sql);
        StringBuilder append = new StringBuilder();
        int start = 0;
        int pos = 0;
        String[] paramNames = new String[INIT_LENGTH];
        while (matcher.find()) {
            append.append(sql, start, matcher.start());
            append.append('?');
            start = matcher.end();
            String param = matcher.group();
            if (pos > paramNames.length - 1) {
                String[] temp = Arrays.copyOf(paramNames, paramNames.length);
                paramNames = new String[paramNames.length + INIT_LENGTH];
                System.arraycopy(temp, 0, paramNames, 0, temp.length);
            }
            paramNames[pos++] = param.substring(2, param.length() - 1); // 去掉#{}
        }
        append.append(sql, start, sql.length());
        sqlObject.setOriginSql(append.toString());
        sqlObject.setParamNames(Arrays.copyOf(paramNames, pos));
    }
}
